package com.itheima.service.impl;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandServiceImpl implements BrandService {
    //获取SqlSessionFactory对象
    private SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public List<Brand> selectAll() {
        SqlSession sqlSession = factory.openSession();
        // 获取BrandMapper代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.selectAll();
        sqlSession.close();
        return brands;
    }

    @Override
    public void add(Brand brand) {
        SqlSession sqlSession = factory.openSession();
        // 获取BrandMapper代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.add(brand);
        // 提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public Brand selectById(String id) {
        SqlSession sqlSession = factory.openSession();
        // 获取BrandMapper代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        Brand brand = mapper.selectById(id);
        sqlSession.close();
        return brand;
    }

    @Override
    public void update(Brand brand) {
        SqlSession sqlSession = factory.openSession();
        // 获取BrandMapper代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.update(brand);
        // 提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void deleteById(String id) {
        SqlSession sqlSession = factory.openSession();
        // 获取BrandMapper代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.deleteById(id);
        // 提交事务
        sqlSession.commit();
        sqlSession.close();
    }
}
